import React,{useState} from 'react'
import {useNavigate} from 'react-router-dom'
import '../assets/css/login.scss'
import api from '../api'
export default function Login() {
  const [name,setName]=useState("")
  const [password,setPassword]=useState("")
  const [loginErrMsg,setLoginErrMsg]=useState("")
  const handleName=e=>setName(e.target.value)
  const handlePwd=e=>setPassword(e.target.value)
  const nav=useNavigate()
  const login=async()=>{
    let result=await api.users.login({account:name,password})
    if(result.code){
        localStorage.setItem('token',result.data.token)
        localStorage.setItem('userInfo',JSON.stringify(result.data.userInfo))
        nav('/home')
    }else{
        setLoginErrMsg(result.msg)
    } 
  }
  return (
    <div className='login-container'>
        <div className="login-box">
            <div className='item'>
                <input type="text" placeholder='请输入用户名' className='txt' onChange={e=>handleName(e)}/>
            </div>
            <div className='item'>
                <input type="text" placeholder='请输入密码' className='txt' onChange={e=>handlePwd(e)}/>
            </div>
            <div className='item'>
                <button className='loginBtn' onClick={login}>登录</button>
            </div>
            <div>
                <span style={{color:'red'}}>{loginErrMsg}</span>
            </div>
        </div>
    </div>
  )
}
